//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package utils.security;

import play.data.parsing.DataParsers;
import utils.Convert;
import utils.io.File;
import utils.io.PropertyFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import play.Logger;
import play.Play;
import play.data.parsing.DataParser;
import play.data.parsing.TextParser;
import play.mvc.Http.Cookie;
import play.mvc.Http.Request;
import play.utils.Utils.Maps;

public class InjectionInterceptor {
    public static Boolean __SYS_SHOVE_FLAG_IsUsed_InjectionInterceptor = false;
    private static Boolean haveBeenRunning = false;
    private static List<String> validImgExtName = null;
    private static final String rule0 = "<[^>]+?style=[\\w]+?:expression\\(|[@][\\s\t\r\n]*import\\b|<[^>]*?\\b(alert|confirm|prompt|javascript|document|cookie|onerror|onmousemove|onload|onclick|onmouseover)\\b[^>]*?>|<[^>]*?(\\\\(u|x|ux)[0-9,a-f,A-F]+?|\\\\[0-9]+?|&#[0-9,a-f,A-F]+?)[^>]*?>|^\\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|/\\*.+?\\*/|<\\s*script\\b|<\\s*iframe\\b|<\\s*frame\\b|<\\s*object\\b|<\\s*embed\\b|<\\s*input\\b|\\bEVAL\\s*\\(|\\bfunction\\b\\s*\\(|<\\s*a\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|[']+?.*?(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b|\\b(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b.*?[']+?";
    private static final String rule1 = "<[^>]+?style=[\\w]+?:expression\\(|[@][\\s\t\r\n]*import\\b|<[^>]*?\\b(alert|confirm|prompt|javascript|document|cookie|onerror|onmousemove|onload|onclick|onmouseover)\\b[^>]*?>|<[^>]*?(\\\\(u|x|ux)[0-9,a-f,A-F]+?|\\\\[0-9]+?|&#[0-9,a-f,A-F]+?)[^>]*?>|^\\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|/\\*.+?\\*/|<\\s*script\\b|<\\s*iframe\\b|<\\s*frame\\b|<\\s*object\\b|<\\s*embed\\b|<\\s*input\\b|\\bEVAL\\s*\\(|\\bfunction\\b\\s*\\(|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|[']+?.*?(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b|\\b(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b.*?[']+?";
    private static Pattern pattern0 = Pattern.compile("<[^>]+?style=[\\w]+?:expression\\(|[@][\\s\t\r\n]*import\\b|<[^>]*?\\b(alert|confirm|prompt|javascript|document|cookie|onerror|onmousemove|onload|onclick|onmouseover)\\b[^>]*?>|<[^>]*?(\\\\(u|x|ux)[0-9,a-f,A-F]+?|\\\\[0-9]+?|&#[0-9,a-f,A-F]+?)[^>]*?>|^\\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|/\\*.+?\\*/|<\\s*script\\b|<\\s*iframe\\b|<\\s*frame\\b|<\\s*object\\b|<\\s*embed\\b|<\\s*input\\b|\\bEVAL\\s*\\(|\\bfunction\\b\\s*\\(|<\\s*a\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|[']+?.*?(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b|\\b(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b.*?[']+?", 2);
    private static Pattern pattern1 = Pattern.compile("<[^>]+?style=[\\w]+?:expression\\(|[@][\\s\t\r\n]*import\\b|<[^>]*?\\b(alert|confirm|prompt|javascript|document|cookie|onerror|onmousemove|onload|onclick|onmouseover)\\b[^>]*?>|<[^>]*?(\\\\(u|x|ux)[0-9,a-f,A-F]+?|\\\\[0-9]+?|&#[0-9,a-f,A-F]+?)[^>]*?>|^\\+/v(8|9)|<[^>]*?=[^>]*?&#[^>]*?>|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|/\\*.+?\\*/|<\\s*script\\b|<\\s*iframe\\b|<\\s*frame\\b|<\\s*object\\b|<\\s*embed\\b|<\\s*input\\b|\\bEVAL\\s*\\(|\\bfunction\\b\\s*\\(|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|[']+?.*?(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b|\\b(OR|AND|[-]{2,}|UPDATE|CREATE|ALTER|DROP|TRUNCATE|SELECT|DELETE|EXEC|INSERT)\\b.*?[']+?", 2);
    private static final String imgRule = "<img\\b[^<>]*?\\bsrc[\\s\t\r\n]*=[\\s\t\r\n]*[\"']?[\\s\t\r\n]*([^\\s\t\r\n\"'<>]*)[^<>]*?/?[\\s\t\r\n]*[/]*>";
    private static Pattern patternImg = Pattern.compile("<img\\b[^<>]*?\\bsrc[\\s\t\r\n]*=[\\s\t\r\n]*[\"']?[\\s\t\r\n]*([^\\s\t\r\n\"'<>]*)[^<>]*?/?[\\s\t\r\n]*[/]*>", 2);
    private Request request = null;
    private Map<String, String[]> parameterMap = null;
    private Map<String, Cookie> cookies = null;
    private String referer = null;
    private static String[] refererArray = null;
    private boolean isKeepStreamOpen = false;

    static {
        PropertyFile propertyFile = null;

        try {
            propertyFile = new PropertyFile();
        } catch (Exception var2) {
            System.err.println(var2);
        }

        if (propertyFile != null) {
            String t_referer = propertyFile.read("injectionInterceptor.referer.whitelist");
            if (StringUtils.isNotBlank(t_referer)) {
                refererArray = t_referer.split(",");
            }
        }

    }

    public boolean getIsKeepStreamOpen() {
        return this.isKeepStreamOpen;
    }

    public void setIsKeepStreamOpen(boolean isKeepStreamOpen) {
        this.isKeepStreamOpen = isKeepStreamOpen;
    }

    public InjectionInterceptor() {
        this.request = Request.current();
        this.initialize();
    }

    private synchronized void initialize() {
        __SYS_SHOVE_FLAG_IsUsed_InjectionInterceptor = Convert.strToBoolean(Play.configuration.getProperty("injectionInterceptor", "true"), true);
        if (__SYS_SHOVE_FLAG_IsUsed_InjectionInterceptor) {
            if (!haveBeenRunning) {
                haveBeenRunning = true;
                validImgExtName = new ArrayList();
                validImgExtName.add(".jpg");
                validImgExtName.add(".jpeg");
                validImgExtName.add(".png");
                validImgExtName.add(".bmp");
                validImgExtName.add(".gif");
                validImgExtName.add(".tif");
                validImgExtName.add(".tiff");
            }
        }
    }

    public void run() throws Exception {
        if (__SYS_SHOVE_FLAG_IsUsed_InjectionInterceptor) {
            if (this.isKeepStreamOpen) {
                InputStream is = this.request.body;
                ByteArrayOutputStream os = new ByteArrayOutputStream();

                try {
                    IOUtils.copy(is, os);
                    this.checkAndParse(new ByteArrayInputStream(os.toByteArray()));
                    this.request.body = new ByteArrayInputStream(os.toByteArray());
                } catch (IOException var12) {
                    ;
                } finally {
                    try {
                        os.close();
                    } catch (Exception var11) {
                        ;
                    }

                }

                this.parameterMap = this.request.params.data;
            } else {
                this.parameterMap = this.request.params.all();
            }

            this.cookies = this.request.cookies;
            this.referer = "" + this.request.headers.get("referer");
            if (!this.parameterMap.isEmpty() || this.cookies != null || this.referer != null) {
                int exceptionLevel = Convert.strToInt(Play.configuration.getProperty(this.request.controller, "0"), 0);
                if (exceptionLevel == 0) {
                    this.intercept(pattern0, false);
                } else if (exceptionLevel == 1) {
                    this.intercept(pattern1, true);
                }

            }
        }
    }

    private boolean intercept(Pattern pattern, Boolean isCheckImg) throws Exception {
        if (this.checkCookies(pattern, isCheckImg)) {
            this.writeResponse("Cookie");
            return true;
        } else if (this.checkReferer(pattern, isCheckImg)) {
            this.writeResponse("Referer");
            return true;
        } else if (this.checkRequest(pattern, isCheckImg)) {
            this.writeResponse("POST、GET");
            return true;
        } else {
            return false;
        }
    }

    private Boolean checkCookies(Pattern pattern, Boolean isCheckImg) {
        if (this.cookies != null && !this.cookies.isEmpty()) {
            Iterator var4 = this.cookies.keySet().iterator();

            while(var4.hasNext()) {
                String key = (String)var4.next();
                if (this._checkData(pattern, ((Cookie)this.cookies.get(key)).value, isCheckImg)) {
                    return true;
                }
            }

            return false;
        } else {
            return false;
        }
    }

    private Boolean checkReferer(Pattern pattern, Boolean isCheckImg) {
        if (this.referer != null && !this.referer.isEmpty()) {
            if (refererArray != null) {
                String[] var6 = refererArray;
                int var5 = refererArray.length;

                for(int var4 = 0; var4 < var5; ++var4) {
                    String str = var6[var4];
                    if (this.referer.startsWith(str)) {
                        return false;
                    }
                }
            }

            return this._checkData(pattern, this.referer, isCheckImg) ? true : false;
        } else {
            return false;
        }
    }

    private Boolean checkRequest(Pattern pattern, Boolean isCheckImg) {
        if (this.parameterMap.isEmpty()) {
            return false;
        } else {
            Set<String> keySet = this.parameterMap.keySet();
            Iterator iterator = keySet.iterator();

            while(iterator.hasNext()) {
                String[] values = (String[])this.parameterMap.get(iterator.next());
                String[] var9 = values;
                int var8 = values.length;

                for(int var7 = 0; var7 < var8; ++var7) {
                    String value = var9[var7];
                    if (this._checkData(pattern, value, isCheckImg)) {
                        return true;
                    }
                }
            }

            return false;
        }
    }

    private Boolean _checkData(Pattern pattern, String value, Boolean isCheckImg) {
        if (value != null && !value.isEmpty()) {
            if (pattern.matcher(value).find()) {
                return true;
            } else if (!isCheckImg) {
                return false;
            } else {
                Matcher m = patternImg.matcher(value);

                while(m.find()) {
                    String fileName = m.group(1);
                    if (!validImgExtName.contains(File.getExtensionName(fileName).toLowerCase())) {
                        return true;
                    }
                }

                return false;
            }
        } else {
            return false;
        }
    }

    private void writeResponse(String checkType) throws Exception {
        String result = "InjectionInterceptorError: 系统检测到您提交的数据中存在恶意的注入型攻击数据(或 img 标签的 src 文件类型不合法)，请检查 " + checkType + " 数据，如果是系统误报，请联系我们处理，谢谢。给您带来了不便，十分抱歉！【技术支持：QQ642161679】";
        Logger.warn("InjectionInterceptorError: " + result + "\r\n" + this.request.url, new Object[0]);
        throw new Exception(result);
    }

    private void checkAndParse(InputStream is) {
        Request request = Request.current();
        String contentType = request.contentType;
        if (contentType != null) {
            DataParser dataParser = DataParsers.forContentType(contentType);
            if (dataParser != null) {
                this._mergeWith(dataParser.parse(is));
            } else if (contentType.startsWith("text/")) {
                this._mergeWith((new TextParser()).parse(is));
            }
        }

        try {
            request.body.close();
        } catch (Exception var5) {
            ;
        }

    }

    void _mergeWith(Map<String, String[]> map) {
        Iterator var3 = map.entrySet().iterator();

        while(var3.hasNext()) {
            Entry<String, String[]> entry = (Entry)var3.next();
            Maps.mergeValueInMap(this.request.params.data, (String)entry.getKey(), (String[])entry.getValue());
        }

    }
}
